package com.engr.springbooteasypoi.thread;


import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SynThread {

    public static void main(String[] args) {

        UserSyn user = new UserSyn("LYX", 10);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 8, 10L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
        MyThread thread1 = new MyThread("线程A：", user, 20);
        MyThread thread2 = new MyThread("线程B：", user, 30);
        MyThread thread3 = new MyThread("线程C：", user, 10);
        MyThread thread4 = new MyThread("线程D：", user, 15);
        MyThread thread5 = new MyThread("线程E：", user, 20);
        MyThread thread6 = new MyThread("线程F：", user, 21);
        poolExecutor.execute(thread1);
        poolExecutor.execute(thread2);
        poolExecutor.execute(thread3);
        poolExecutor.execute(thread4);
        poolExecutor.execute(thread5);
        poolExecutor.execute(thread6);
        poolExecutor.shutdown();
    }
}

class MyThread extends Thread {

    private UserSyn u;
    private int y = 0;

    MyThread(String name, UserSyn u, int y) {
        super(name);
        this.u = u;
        this.y = y;
    }

    public void run() {
        u.oper(y);

    }
}

class UserSyn {

    private String code;

    private int cash;

    public UserSyn(String code, int cash) {
        this.code = code;
        this.cash = cash;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public int getCash() {
        return cash;
    }

    public void setCash(int cash) {
        this.cash = cash;
    }

    /**
     * 业务方法 添加 X 万元
     */
    public void oper(int x) {
        try {
            Thread.sleep(10L);
            synchronized (this) {
                this.cash += x;
                System.out.println(Thread.currentThread().getName() + " 运行结束,增加 " + x + ",当前账户余额为: " + cash);
            }
            Thread.sleep(10L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "UserSyn{" +
                "code='" + code + '\'' +
                ", cash=" + cash +
                '}';
    }
}